home *** CD-ROM | disk | FTP | other *** search
/ AmigActive 2 / AACD 2.iso / AACD / Programming / perlman / man / perlipc.txt < prev    next >
Encoding:
Text File  |  1999-09-09  |  37.2 KB  |  960 lines

  1. NAME
  2.        perlipc - Perl interprocess communication (signals, fifos,
  3.        pipes, safe subprocceses, sockets, and semaphores)
  4.  
  5. DESCRIPTION
  6.        The basic IPC facilities of Perl are built out of the good
  7.        old Unix signals, named pipes, pipe opens, the Berkeley
  8.        socket routines, and SysV IPC calls.  Each is used in
  9.        slightly different situations.
  10.  
  11. Signals
  12.        Perl uses a simple signal handling model: the %SIG hash
  13.        contains names or references of user-installed signal
  14.        handlers.  These handlers will be called with an argument
  15.        which is the name of the signal that triggered it.  A
  16.        signal may be generated intentionally from a particular
  17.        keyboard sequence like control-C or control-Z, sent to you
  18.        from an another process, or triggered automatically by the
  19.        kernel when special events transpire, like a child process
  20.        exiting, your process running out of stack space, or
  21.        hitting file size limit.
  22.  
  23.        For example, to trap an interrupt signal, set up a handler
  24.        like this.  Notice how all we do is set with a global
  25.        variable and then raise an exception.  That's because on
  26.        most systems libraries are not re-entrant, so calling any
  27.        print() functions (or even anything that needs to
  28.        malloc(3) more memory) could in theory trigger a memory
  29.        fault and subsequent core dump.
  30.  
  31.            sub catch_zap {
  32.                my $signame = shift;
  33.                $shucks++;
  34.                die "Somebody sent me a SIG$signame";
  35.            }
  36.            $SIG{INT} = 'catch_zap';  # could fail in modules
  37.            $SIG{INT} = \&catch_zap;  # best strategy
  38.  
  39.        The names of the signals are the ones listed out by kill
  40.        -l on your system, or you can retrieve them from the
  41.        Config module.  Set up an @signame list indexed by number
  42.        to get the name and a %signo table indexed by name to get
  43.        the number:
  44.  
  45.            use Config;
  46.            defined $Config{sig_name} || die "No sigs?";
  47.            foreach $name (split(' ', $Config{sig_name})) {
  48.                $signo{$name} = $i;
  49.                $signame[$i] = $name;
  50.                $i++;
  51.            }
  52.  
  53.        So to check whether signal 17 and SIGALRM were the same,
  54.        just do this:
  55.            print "signal #17 = $signame[17]\n";
  56.            if ($signo{ALRM}) {
  57.                print "SIGALRM is $signo{ALRM}\n";
  58.            }
  59.  
  60.        You may also choose to assign the strings 'IGNORE' or
  61.        'DEFAULT' as the handler, in which case Perl will try to
  62.        discard the signal or do the default thing.  Some signals
  63.        can be neither trapped nor ignored, such as the KILL and
  64.        STOP (but not the TSTP) signals.  One strategy for
  65.        temporarily ignoring signals is to use a local()
  66.        statement, which will be automatically restored once your
  67.        block is exited.  (Remember that local() values are
  68.        "inherited" by functions called from within that block.)
  69.  
  70.            sub precious {
  71.                local $SIG{INT} = 'IGNORE';
  72.                &more_functions;
  73.            }
  74.            sub more_functions {
  75.                # interrupts still ignored, for now...
  76.            }
  77.  
  78.        Sending a signal to a negative process ID means that you
  79.        send the signal to the entire Unix process-group.  This
  80.        code send a hang-up signal to all processes in the current
  81.        process group except for the current process itself:
  82.  
  83.            {
  84.                local $SIG{HUP} = 'IGNORE';
  85.                kill HUP => -$$;
  86.                # snazzy writing of: kill('HUP', -$$)
  87.            }
  88.  
  89.        Another interesting signal to send is signal number zero.
  90.        This doesn't actually affect another process, but instead
  91.        checks whether it's alive or has changed its UID.
  92.  
  93.            unless (kill 0 => $kid_pid) {
  94.                warn "something wicked happened to $kid_pid";
  95.            }
  96.  
  97.        You might also want to employ anonymous functions for
  98.        simple signal handlers:
  99.  
  100.            $SIG{INT} = sub { die "\nOutta here!\n" };
  101.  
  102.        But that will be problematic for the more complicated
  103.        handlers that need to re-install themselves.  Because
  104.        Perl's signal mechanism is currently based on the
  105.        signal(3) function from the C library, you may somtimes be
  106.        so misfortunate as to run on systems where that function
  107.        is "broken", that is, it behaves in the old unreliable
  108.        SysV way rather than the newer, more reasonable BSD and
  109.        POSIX fashion.  So you'll see defensive people writing
  110.        signal handlers like this:
  111.  
  112.            sub REAPER {
  113.                $SIG{CHLD} = \&REAPER;  # loathe sysV
  114.                $waitedpid = wait;
  115.            }
  116.            $SIG{CHLD} = \&REAPER;
  117.            # now do something that forks...
  118.  
  119.        or even the more elaborate:
  120.  
  121.            use POSIX "wait_h";
  122.            sub REAPER {
  123.                my $child;
  124.                $SIG{CHLD} = \&REAPER;  # loathe sysV
  125.                while ($child = waitpid(-1,WNOHANG)) {
  126.                    $Kid_Status{$child} = $?;
  127.                }
  128.            }
  129.            $SIG{CHLD} = \&REAPER;
  130.            # do something that forks...
  131.  
  132.        Signal handling is also used for timeouts in Unix,   While
  133.        safely protected within an eval{} block, you set a signal
  134.        handler to trap alarm signals and then schedule to have
  135.        one delivered to you in some number of seconds.  Then try
  136.        your blocking operation, clearing the alarm when it's done
  137.        but not before you've exited your eval{} block.  If it
  138.        goes off, you'll use die() to jump out of the block, much
  139.        as you might using longjmp() or throw() in other
  140.        languages.
  141.  
  142.        Here's an example:
  143.  
  144.            eval {
  145.                local $SIG{ALRM} = sub { die "alarm clock restart" };
  146.                alarm 10;
  147.                flock(FH, 2);   # blocking write lock
  148.                alarm 0;
  149.            };
  150.            if ($@ and $@ !~ /alarm clock restart/) { die }
  151.  
  152.        For more complex signal handling, you might see the
  153.        standard POSIX module.  Lamentably, this is almost
  154.        entirely undocumented, but the t/lib/posix.t file from the
  155.        Perl source distribution has some examples in it.
  156.  
  157. Named Pipes
  158.        A named pipe (often referred to as a FIFO) is an old Unix
  159.        IPC mechanism for processes communicating on the same
  160.        machine.  It works just like a regular, connected
  161.        anonymous pipes, except that the processes rendezvous
  162.        using a filename and don't have to be related.
  163.        To create a named pipe, use the Unix command mknod(1) or
  164.        on some systems, mkfifo(1).  These may not be in your
  165.        normal path.
  166.  
  167.            # system return val is backwards, so && not ||
  168.            #
  169.            $ENV{PATH} .= ":/etc:/usr/etc";
  170.            if  (      system('mknod',  $path, 'p')
  171.                    && system('mkfifo', $path) )
  172.            {
  173.                die "mk{nod,fifo} $path failed;
  174.            }
  175.  
  176.        A fifo is convenient when you want to connect a process to
  177.        an unrelated one.  When you open a fifo, the program will
  178.        block until there's something on the other end.
  179.  
  180.        For example, let's say you'd like to have your .signature
  181.        file be a named pipe that has a Perl program on the other
  182.        end.  Now every time any program (like a mailer,
  183.        newsreader, finger program, etc.) tries to read from that
  184.        file, the reading program will block and your program will
  185.        supply the the new signature.  We'll use the pipe-checking
  186.        file test -p to find out whether anyone (or anything) has
  187.        accidentally removed our fifo.
  188.  
  189.            chdir; # go home
  190.            $FIFO = '.signature';
  191.            $ENV{PATH} .= ":/etc:/usr/games";
  192.  
  193.            while (1) {
  194.                unless (-p $FIFO) {
  195.                    unlink $FIFO;
  196.                    system('mknod', $FIFO, 'p')
  197.                        && die "can't mknod $FIFO: $!";
  198.                }
  199.  
  200.                # next line blocks until there's a reader
  201.                open (FIFO, "> $FIFO") || die "can't write $FIFO: $!";
  202.                print FIFO "John Smith (smith\@host.org)\n", `fortune -s`;
  203.                close FIFO;
  204.                sleep 2;    # to avoid dup sigs
  205.            }
  206.  
  207. Using open() for IPC
  208.        Perl's basic open() statement can also be used for
  209.        unidirectional interprocess communication by either
  210.        appending or prepending a pipe symbol to the second
  211.        argument to open().  Here's how to start something up a
  212.        child process you intend to write to:
  213.  
  214.            open(SPOOLER, "| cat -v | lpr -h 2>/dev/null")
  215.                            || die "can't fork: $!";
  216.            local $SIG{PIPE} = sub { die "spooler pipe broke" };
  217.            print SPOOLER "stuff\n";
  218.            close SPOOLER || die "bad spool: $! $?";
  219.  
  220.        And here's how to start up a child process you intend to
  221.        read from:
  222.  
  223.            open(STATUS, "netstat -an 2>&1 |")
  224.                            || die "can't fork: $!";
  225.            while (<STATUS>) {
  226.                next if /^(tcp|udp)/;
  227.                print;
  228.            }
  229.            close SPOOLER || die "bad netstat: $! $?";
  230.  
  231.        If one can be sure that a particular program is a Perl
  232.        script that is expecting filenames in @ARGV, the clever
  233.        programmer can write something like this:
  234.  
  235.            $ program f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile
  236.  
  237.        and irrespective of which shell it's called from, the Perl
  238.        program will read from the file f1, the process cmd1,
  239.        standard input (tmpfile in this case), the f2 file, the
  240.        cmd2 command, and finally the f3 file.  Pretty nifty, eh?
  241.  
  242.        You might notice that you could use backticks for much the
  243.        same effect as opening a pipe for reading:
  244.  
  245.            print grep { !/^(tcp|udp)/ } `netstat -an 2>&1`;
  246.            die "bad netstat" if $?;
  247.  
  248.        While this is true on the surface, it's much more
  249.        efficient to process the file one line or record at a time
  250.        because then you don't have to read the whole thing into
  251.        memory at once. It also gives you finer control of the
  252.        whole process, letting you to kill off the child process
  253.        early if you'd like.
  254.  
  255.        Be careful to check both the open() and the close() return
  256.        values.  If you're writing to a pipe, you should also trap
  257.        SIGPIPE.  Otherwise, think of what happens when you start
  258.        up a pipe to a command that doesn't exist: the open() will
  259.        in all likelihood succeed (it only reflects the fork()'s
  260.        success), but then your output will fail--spectacularly.
  261.        Perl can't know whether the command worked because your
  262.        command is actually running in a separate process whose
  263.        exec() might have failed.  Therefore, while readers of
  264.        bogus commands just return a quick end of file, writers to
  265.        bogus command will trigger a signal they'd better be
  266.        prepared to handle.  Consider:
  267.  
  268.            open(FH, "|bogus");
  269.            print FH "bang\n";
  270.            close FH;
  271.  
  272.        Safe Pipe Opens
  273.  
  274.        Another interesting approach to IPC is making your single
  275.        program go multiprocess and communicate between (or even
  276.        amongst) yourselves.  The open() function will accept a
  277.        file argument of either "-|" or "|-" to do a very
  278.        interesting thing: it forks a child connected to the
  279.        filehandle you've opened.  The child is running the same
  280.        program as the parent.  This is useful for safely opening
  281.        a file when running under an assumed UID or GID, for
  282.        example.  If you open a pipe to minus, you can write to
  283.        the filehandle you opened and your kid will find it in his
  284.        STDIN.  If you open a pipe from minus, you can read from
  285.        the filehandle you opened whatever your kid writes to his
  286.        STDOUT.
  287.  
  288.            use English;
  289.            my $sleep_count = 0;
  290.  
  291.            do {
  292.                $pid = open(KID_TO_WRITE, "|-");
  293.                unless (defined $pid) {
  294.                    warn "cannot fork: $!";
  295.                    die "bailing out" if $sleep_count++ > 6;
  296.                    sleep 10;
  297.                }
  298.            } until defined $pid;
  299.  
  300.            if ($pid) {  # parent
  301.                print KID_TO_WRITE @some_data;
  302.                close(KID_TO_WRITE) || warn "kid exited $?";
  303.            } else {     # child
  304.                ($EUID, $EGID) = ($UID, $GID); # suid progs only
  305.                open (FILE, "> /safe/file")
  306.                    || die "can't open /safe/file: $!";
  307.                while (<STDIN>) {
  308.                    print FILE; # child's STDIN is parent's KID
  309.                }
  310.                exit;  # don't forget this
  311.            }
  312.  
  313.        Another common use for this construct is when you need to
  314.        execute something without the shell's interference.  With
  315.        system(), it's straigh-forward, but you can't use a pipe
  316.        open or backticks safely.  That's because there's no way
  317.        to stop the shell from getting its hands on your
  318.        arguments.   Instead, use lower-level control to call
  319.        exec() directly.
  320.  
  321.        Here's a safe backtick or pipe open for read:
  322.  
  323.            # add error processing as above
  324.            $pid = open(KID_TO_READ, "-|");
  325.  
  326.            if ($pid) {   # parent
  327.                while (<KID_TO_READ>) {
  328.                    # do something interesting
  329.                }
  330.                close(KID_TO_READ) || warn "kid exited $?";
  331.  
  332.            } else {      # child
  333.                ($EUID, $EGID) = ($UID, $GID); # suid only
  334.                exec($program, @options, @args)
  335.                    || die "can't exec program: $!";
  336.                # NOTREACHED
  337.            }
  338.  
  339.        And here's a safe pipe open for writing:
  340.  
  341.            # add error processing as above
  342.            $pid = open(KID_TO_WRITE, "|-");
  343.            $SIG{ALRM} = sub { die "whoops, $program pipe broke" };
  344.  
  345.            if ($pid) {  # parent
  346.                for (@data) {
  347.                    print KID_TO_WRITE;
  348.                }
  349.                close(KID_TO_WRITE) || warn "kid exited $?";
  350.  
  351.            } else {     # child
  352.                ($EUID, $EGID) = ($UID, $GID);
  353.                exec($program, @options, @args)
  354.                    || die "can't exec program: $!";
  355.                # NOTREACHED
  356.            }
  357.  
  358.        Note that these operations are full Unix forks, which
  359.        means they may not be correctly implemented on alien
  360.        systems.  Additionally, these are not true multithreading.
  361.        If you'd like to learn more about threading, see the
  362.        modules file mentioned below in the the section on SEE
  363.        ALSO section.
  364.  
  365.        Bidirectional Communication
  366.  
  367.        While this works reasonably well for unidirectional
  368.        communication, what about bidirectional communication?
  369.        The obvious thing you'd like to do doesn't actually work:
  370.  
  371.            open(PROG_FOR_READING_AND_WRITING, "| some program |")
  372.  
  373.        and if you forget to use the -w flag, then you'll miss out
  374.        entirely on the diagnostic message:
  375.            Can't do bidirectional pipe at -e line 1.
  376.  
  377.        If you really want to, you can use the standard open2()
  378.        library function to catch both ends.  There's also an
  379.        open3() for tridirectional I/O so you can also catch your
  380.        child's STDERR, but doing so would then require an awkward
  381.        select() loop and wouldn't allow you to use normal Perl
  382.        input operations.
  383.  
  384.        If you look at its source, you'll see that open2() uses
  385.        low-level primitives like Unix pipe() and exec() to create
  386.        all the connections.  While it might have been slightly
  387.        more efficient by using socketpair(), it would have then
  388.        been even less portable than it already is.  The open2()
  389.        and open3() functions are  unlikely to work anywhere
  390.        except on a Unix system or some other one purporting to be
  391.        POSIX compliant.
  392.  
  393.        Here's an example of using open2():
  394.  
  395.            use FileHandle;
  396.            use IPC::Open2;
  397.            $pid = open2( \*Reader, \*Writer, "cat -u -n" );
  398.            Writer->autoflush(); # default here, actually
  399.            print Writer "stuff\n";
  400.            $got = <Reader>;
  401.  
  402.        The problem with this is that Unix buffering is going to
  403.        really ruin your day.  Even though your Writer filehandle
  404.        is autoflushed, and the process on the other end will get
  405.        your data in a timely manner, you can't usually do
  406.        anything to force it to actually give it back to you in a
  407.        similarly quick fashion.  In this case, we could, because
  408.        we gave cat a -u flag to make it unbuffered.  But very few
  409.        Unix commands are designed to operate over pipes, so this
  410.        seldom works unless you yourself wrote the program on the
  411.        other end of the double-ended pipe.
  412.  
  413.        A solution to this is the non-standard Comm.pl library.
  414.        It uses pseudo-ttys to make your program behave more
  415.        reasonably:
  416.  
  417.            require 'Comm.pl';
  418.            $ph = open_proc('cat -n');
  419.            for (1..10) {
  420.                print $ph "a line\n";
  421.                print "got back ", scalar <$ph>;
  422.            }
  423.  
  424.        This way you don't have to have control over the source
  425.        code of the program you're using.  The Comm library also
  426.        has expect() and interact() functions.  Find the library
  427.        (and hopefully its successor IPC::Chat) at your nearest
  428.        CPAN archive as detailed in the the section on SEE ALSO
  429.        section below.
  430.  
  431. Sockets: Client/Server Communication
  432.        While not limited to Unix-derived operating systems (e.g.
  433.        WinSock on PCs provides socket support, as do some VMS
  434.        libraries), you may not have sockets on your system, in
  435.        which this section probably isn't going to do you much
  436.        good.  With sockets, you can do both virtual circuits
  437.        (i.e. TCP streams) and datagrams (i.e. UDP packets).  You
  438.        may be able to do even more depending on your system.
  439.  
  440.        The Perl function calls for dealing with sockets have the
  441.        same names as the corresponding system calls in C, but
  442.        their arguments tend to differ for two reasons: first,
  443.        Perl filehandles work differently than C file descriptors.
  444.        Second, Perl already knows the length of its strings, so
  445.        you don't need to pass that information.
  446.  
  447.        One of the major problems with old socket code in Perl was
  448.        that it used hard-coded values for some of the constants,
  449.        which severely hurt portability.  If you ever see code
  450.        that does anything like explicitly setting $AF_INET = 2,
  451.        you know you're in for big trouble:  An immeasurably
  452.        superior approach is to use the Socket module, which more
  453.        reliably grants access to various constants and functions
  454.        you'll need.
  455.  
  456.        Internet TCP Clients and Servers
  457.  
  458.        Use Internet-domain sockets when you want to do client-
  459.        server communication that might extend to machines outside
  460.        of your own system.
  461.  
  462.        Here's a sample TCP client using Internet-domain sockets:
  463.  
  464.            #!/usr/bin/perl -w
  465.            require 5.002;
  466.            use strict;
  467.            use Socket;
  468.            my ($remote,$port, $iaddr, $paddr, $proto, $line);
  469.  
  470.            $remote  = shift || 'localhost';
  471.            $port    = shift || 2345;  # random port
  472.            if ($port =~ /\D/) { $port = getservbyname($port, 'tcp') }
  473.            die "No port" unless $port;
  474.            $iaddr   = inet_aton($remote)               || die "no host: $remote";
  475.            $paddr   = sockaddr_in($port, $iaddr);
  476.  
  477.            $proto   = getprotobyname('tcp');
  478.            socket(SOCK, PF_INET, SOCK_STREAM, $proto)  || die "socket: $!";
  479.            connect(SOCK, $paddr)    || die "connect: $!";
  480.            while ($line = <SOCK>) {
  481.                print $line;
  482.            }
  483.            close (SOCK)            || die "close: $!";
  484.            exit;
  485.  
  486.        And here's a corresponding server to go along with it.
  487.        We'll leave the address as INADDR_ANY so that the kernel
  488.        can choose the appropriate interface on multihomed hosts.
  489.        If you want sit on a particular interface (like the
  490.        external side of a gateway or firewall machine), you
  491.        should fill this in with your real address instead.
  492.  
  493.            #!/usr/bin/perl -Tw
  494.            require 5.002;
  495.            use strict;
  496.            BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  497.            use Socket;
  498.            use Carp;
  499.  
  500.            sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  501.  
  502.            my $port = shift || 2345;
  503.            my $proto = getprotobyname('tcp');
  504.            socket(Server, PF_INET, SOCK_STREAM, $proto)        || die "socket: $!";
  505.            setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
  506.                                                pack("l", 1))   || die "setsockopt: $!";
  507.            bind(Server, sockaddr_in($port, INADDR_ANY))        || die "bind: $!";
  508.            listen(Server,SOMAXCONN)                            || die "listen: $!";
  509.  
  510.            logmsg "server started on port $port";
  511.  
  512.            my $paddr;
  513.  
  514.            $SIG{CHLD} = \&REAPER;
  515.  
  516.            for ( ; $paddr = accept(Client,Server); close Client) {
  517.                my($port,$iaddr) = sockaddr_in($paddr);
  518.                my $name = gethostbyaddr($iaddr,AF_INET);
  519.  
  520.                logmsg "connection from $name [",
  521.                        inet_ntoa($iaddr), "]
  522.                        at port $port";
  523.  
  524.                print CLIENT "Hello there, $name, it's now ",
  525.                                scalar localtime, "\n";
  526.            }
  527.  
  528.        And here's a multithreaded version.  It's multithreaded in
  529.        that like most typical servers, it spawns (forks) a slave
  530.        server to handle the client request so that the master
  531.        server can quickly go back to service a new client.
  532.  
  533.            #!/usr/bin/perl -Tw
  534.            require 5.002;
  535.            use strict;
  536.            BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  537.            use Socket;
  538.            use Carp;
  539.  
  540.            sub spawn;  # forward declaration
  541.            sub logmsg { print "$0 $$: @_ at ", scalar localtime, "\n" }
  542.  
  543.            my $port = shift || 2345;
  544.            my $proto = getprotobyname('tcp');
  545.            socket(Server, PF_INET, SOCK_STREAM, $proto)        || die "socket: $!";
  546.            setsockopt(Server, SOL_SOCKET, SO_REUSEADDR,
  547.                                                pack("l", 1))   || die "setsockopt: $!";
  548.            bind(Server, sockaddr_in($port, INADDR_ANY))        || die "bind: $!";
  549.            listen(Server,SOMAXCONN)                            || die "listen: $!";
  550.  
  551.            logmsg "server started on port $port";
  552.  
  553.            my $waitedpid = 0;
  554.            my $paddr;
  555.  
  556.            sub REAPER {
  557.                $SIG{CHLD} = \&REAPER;  # loathe sysV
  558.                $waitedpid = wait;
  559.                logmsg "reaped $waitedpid" . ($? ? " with exit $?" : '');
  560.            }
  561.  
  562.            $SIG{CHLD} = \&REAPER;
  563.  
  564.            for ( $waitedpid = 0;
  565.                  ($paddr = accept(Client,Server)) || $waitedpid;
  566.                  $waitedpid = 0, close Client)
  567.            {
  568.                next if $waitedpid;
  569.                my($port,$iaddr) = sockaddr_in($paddr);
  570.                my $name = gethostbyaddr($iaddr,AF_INET);
  571.  
  572.                logmsg "connection from $name [",
  573.                        inet_ntoa($iaddr), "]
  574.                        at port $port";
  575.  
  576.                spawn sub {
  577.                    print "Hello there, $name, it's now ", scalar localtime, "\n";
  578.                    exec '/usr/games/fortune'
  579.                        or confess "can't exec fortune: $!";
  580.                };
  581.  
  582.            }
  583.  
  584.            sub spawn {
  585.                my $coderef = shift;
  586.  
  587.                unless (@_ == 0 && $coderef && ref($coderef) eq 'CODE') {
  588.                    confess "usage: spawn CODEREF";
  589.                }
  590.  
  591.                my $pid;
  592.                if (!defined($pid = fork)) {
  593.                    logmsg "cannot fork: $!";
  594.                    return;
  595.                } elsif ($pid) {
  596.                    logmsg "begat $pid";
  597.                    return; # i'm the parent
  598.                }
  599.                # else i'm the child -- go spawn
  600.  
  601.                open(STDIN,  "<&Client")   || die "can't dup client to stdin";
  602.                open(STDOUT, ">&Client")   || die "can't dup client to stdout";
  603.                ## open(STDERR, ">&STDOUT") || die "can't dup stdout to stderr";
  604.                exit &$coderef();
  605.            }
  606.  
  607.        This server takes the trouble to clone off a child version
  608.        via fork() for each incoming request.  That way it can
  609.        handle many requests at once, which you might not always
  610.        want.  Even if you don't fork(), the listen() will allow
  611.        that many pending connections.  Forking servers have to be
  612.        particularly careful about cleaning up their dead children
  613.        (called "zombies" in Unix parlance), because otherwise
  614.        you'll quickly fill up your process table.
  615.  
  616.        We suggest that you use the -T flag to use taint checking
  617.        (see the perlsec manpage) even if we aren't running setuid
  618.        or setgid.  This is always a good idea for servers and
  619.        other programs run on behalf of someone else (like CGI
  620.        scripts), because it lessens the chances that people from
  621.        the outside will be able to compromise your system.
  622.  
  623.        Let's look at another TCP client.  This one connects to
  624.        the TCP "time" service on a number of different machines
  625.        and shows how far their clocks differ from the system on
  626.        which it's being run:
  627.  
  628.            #!/usr/bin/perl  -w
  629.            require 5.002;
  630.            use strict;
  631.            use Socket;
  632.  
  633.            my $SECS_of_70_YEARS = 2208988800;
  634.            sub ctime { scalar localtime(shift) }
  635.  
  636.            my $iaddr = gethostbyname('localhost');
  637.            my $proto = getprotobyname('tcp');
  638.            my $port = getservbyname('time', 'tcp');
  639.            my $paddr = sockaddr_in(0, $iaddr);
  640.            my($host);
  641.            $| = 1;
  642.            printf "%-24s %8s %s\n",  "localhost", 0, ctime(time());
  643.  
  644.            foreach $host (@ARGV) {
  645.                printf "%-24s ", $host;
  646.                my $hisiaddr = inet_aton($host)     || die "unknown host";
  647.                my $hispaddr = sockaddr_in($port, $hisiaddr);
  648.                socket(SOCKET, PF_INET, SOCK_STREAM, $proto)   || die "socket: $!";
  649.                connect(SOCKET, $hispaddr)          || die "bind: $!";
  650.                my $rtime = '    ';
  651.                read(SOCKET, $rtime, 4);
  652.                close(SOCKET);
  653.                my $histime = unpack("N", $rtime) - $SECS_of_70_YEARS ;
  654.                printf "%8d %s\n", $histime - time, ctime($histime);
  655.            }
  656.  
  657.        Unix-Domain TCP Clients and Servers
  658.  
  659.        That's fine for Internet-domain clients and servers, but
  660.        what local communications?  While you can use the same
  661.        setup, sometimes you don't want to.  Unix-domain sockets
  662.        are local to the current host, and are often used
  663.        internally to implement pipes.  Unlike Internet domain
  664.        sockets, UNIX domain sockets can show up in the file
  665.        system with an ls(1) listing.
  666.  
  667.            $ ls -l /dev/log
  668.            srw-rw-rw-  1 root            0 Oct 31 07:23 /dev/log
  669.  
  670.        You can test for these with Perl's -S file test:
  671.  
  672.            unless ( -S '/dev/log' ) {
  673.                die "something's wicked with the print system";
  674.            }
  675.  
  676.        Here's a sample Unix-domain client:
  677.  
  678.            #!/usr/bin/perl -w
  679.            require 5.002;
  680.            use Socket;
  681.            use strict;
  682.            my ($rendezvous, $line);
  683.  
  684.            $rendezvous = shift || '/tmp/catsock';
  685.            socket(SOCK, PF_UNIX, SOCK_STREAM, 0)       || die "socket: $!";
  686.            connect(SOCK, sockaddr_un($remote))         || die "connect: $!";
  687.            while ($line = <SOCK>) {
  688.                print $line;
  689.            }
  690.            exit;
  691.  
  692.        And here's a corresponding server.
  693.  
  694.            #!/usr/bin/perl -Tw
  695.            require 5.002;
  696.            use strict;
  697.            use Socket;
  698.            use Carp;
  699.  
  700.            BEGIN { $ENV{PATH} = '/usr/ucb:/bin' }
  701.  
  702.            my $NAME = '/tmp/catsock';
  703.            my $uaddr = sockaddr_un($NAME);
  704.            my $proto = getprotobyname('tcp');
  705.  
  706.            socket(Server,PF_UNIX,SOCK_STREAM,0)        || die "socket: $!";
  707.            unlink($NAME);
  708.            bind  (Server, $uaddr)                      || die "bind: $!";
  709.            listen(Server,SOMAXCONN)                    || die "listen: $!";
  710.  
  711.            logmsg "server started on $NAME";
  712.  
  713.            $SIG{CHLD} = \&REAPER;
  714.  
  715.            for ( $waitedpid = 0;
  716.                  accept(Client,Server) || $waitedpid;
  717.                  $waitedpid = 0, close Client)
  718.            {
  719.                next if $waitedpid;
  720.                logmsg "connection on $NAME";
  721.                spawn sub {
  722.                    print "Hello there, it's now ", scalar localtime, "\n";
  723.                    exec '/usr/games/fortune' or die "can't exec fortune: $!";
  724.                };
  725.            }
  726.  
  727.        As you see, it's remarkably similar to the Internet domain
  728.        TCP server, so much so, in fact, that we've omitted
  729.        several duplicate functions--spawn(), logmsg(), ctime(),
  730.        and REAPER()--which are exactly the same as in the other
  731.        server.
  732.  
  733.        So why would you ever want to use a Unix domain socket
  734.        instead of a simpler named pipe?  Because a named pipe
  735.        doesn't give you sessions.  You can't tell one process's
  736.        data from another's.  With socket programming, you get a
  737.        separate session for each client: that's why accept()
  738.        takes two arguments.
  739.  
  740.        For example, let's say that you have a long running
  741.        database server daemon that you want folks from the World
  742.        Wide Web to be able to access, but only if they go through
  743.        a CGI interface.  You'd have a small, simple CGI program
  744.        that does whatever checks and logging you feel like, and
  745.        then acts as a Unix-domain client and connects to your
  746.        private server.
  747.  
  748.        UDP: Message Passing
  749.  
  750.        Another kind of client-server setup is one that uses not
  751.        connections, but messages.  UDP communications involve
  752.        much lower overhead but also provide less reliability, as
  753.        there are no promises that messages will arrive at all,
  754.        let alone in order and unmangled.  Still, UDP offers some
  755.        advantages over TCP, including being able to "broadcast"
  756.        or "multicast" to a whole bunch of destination hosts at
  757.        once (usually on your local subnet).  If you find yourself
  758.        overly concerned about reliability and start building
  759.        checks into your message system, then you probably should
  760.        just use TCP to start with.
  761.  
  762.        Here's a UDP program similar to the sample Internet TCP
  763.        client given above.  However, instead of checking one host
  764.        at a time, the UDP version will check many of them
  765.        asynchronously by simulating a multicast and then using
  766.        select() to do a timed-out wait for I/O.  To do something
  767.        similar with TCP, you'd have to use a different socket
  768.        handle for each host.
  769.  
  770.            #!/usr/bin/perl -w
  771.            use strict;
  772.            require 5.002;
  773.            use Socket;
  774.            use Sys::Hostname;
  775.  
  776.            my ( $count, $hisiaddr, $hispaddr, $histime,
  777.                 $host, $iaddr, $paddr, $port, $proto,
  778.                 $rin, $rout, $rtime, $SECS_of_70_YEARS);
  779.  
  780.            $SECS_of_70_YEARS      = 2208988800;
  781.  
  782.            $iaddr = gethostbyname(hostname());
  783.            $proto = getprotobyname('udp');
  784.            $port = getservbyname('time', 'udp');
  785.            $paddr = sockaddr_in(0, $iaddr); # 0 means let kernel pick
  786.  
  787.            socket(SOCKET, PF_INET, SOCK_DGRAM, $proto)   || die "socket: $!";
  788.            bind(SOCKET, $paddr)                          || die "bind: $!";
  789.  
  790.            $| = 1;
  791.            printf "%-12s %8s %s\n",  "localhost", 0, scalar localtime time;
  792.            $count = 0;
  793.            for $host (@ARGV) {
  794.                $count++;
  795.                $hisiaddr = inet_aton($host)    || die "unknown host";
  796.                $hispaddr = sockaddr_in($port, $hisiaddr);
  797.                defined(send(SOCKET, 0, 0, $hispaddr))    || die "send $host: $!";
  798.            }
  799.  
  800.            $rin = '';
  801.            vec($rin, fileno(SOCKET), 1) = 1;
  802.            # timeout after 10.0 seconds
  803.            while ($count && select($rout = $rin, undef, undef, 10.0)) {
  804.                $rtime = '';
  805.                ($hispaddr = recv(SOCKET, $rtime, 4, 0))        || die "recv: $!";
  806.                ($port, $hisiaddr) = sockaddr_in($hispaddr);
  807.                $host = gethostbyaddr($hisiaddr, AF_INET);
  808.                $histime = unpack("N", $rtime) - $SECS_of_70_YEARS ;
  809.                printf "%-12s ", $host;
  810.                printf "%8d %s\n", $histime - time, scalar localtime($histime);
  811.                $count--;
  812.            }
  813.  
  814. SysV IPC
  815.        While System V IPC isn't so widely used as sockets, it
  816.        still has some interesting uses.  You can't, however,
  817.        effectively use SysV IPC or Berkeley mmap() to have shared
  818.        memory so as to share a variable amongst several
  819.        processes.  That's because Perl would reallocate your
  820.        string when you weren't wanting it to.
  821.  
  822.        Here's a small example showing shared memory usage.
  823.  
  824.            $IPC_PRIVATE = 0;
  825.            $IPC_RMID = 0;
  826.            $size = 2000;
  827.            $key = shmget($IPC_PRIVATE, $size , 0777 );
  828.            die unless defined $key;
  829.  
  830.            $message = "Message #1";
  831.            shmwrite($key, $message, 0, 60 ) || die "$!";
  832.            shmread($key,$buff,0,60) || die "$!";
  833.  
  834.            print $buff,"\n";
  835.  
  836.            print "deleting $key\n";
  837.            shmctl($key ,$IPC_RMID, 0) || die "$!";
  838.  
  839.        Here's an example of a semaphore:
  840.  
  841.            $IPC_KEY = 1234;
  842.            $IPC_RMID = 0;
  843.            $IPC_CREATE = 0001000;
  844.            $key = semget($IPC_KEY, $nsems , 0666 | $IPC_CREATE );
  845.            die if !defined($key);
  846.            print "$key\n";
  847.  
  848.        Put this code in a separate file to be run in more that
  849.        one process Call the file take:
  850.  
  851.            # create a semaphore
  852.  
  853.            $IPC_KEY = 1234;
  854.            $key = semget($IPC_KEY,  0 , 0 );
  855.            die if !defined($key);
  856.  
  857.            $semnum = 0;
  858.            $semflag = 0;
  859.  
  860.            # 'take' semaphore
  861.            # wait for semaphore to be zero
  862.            $semop = 0;
  863.            $opstring1 = pack("sss", $semnum, $semop, $semflag);
  864.  
  865.            # Increment the semaphore count
  866.            $semop = 1;
  867.            $opstring2 = pack("sss", $semnum, $semop,  $semflag);
  868.            $opstring = $opstring1 . $opstring2;
  869.  
  870.            semop($key,$opstring) || die "$!";
  871.  
  872.        Put this code in a separate file to be run in more that
  873.        one process Call this file give:
  874.  
  875.            # 'give' the semaphore
  876.            # run this in the original process and you will see
  877.            # that the second process continues
  878.  
  879.            $IPC_KEY = 1234;
  880.            $key = semget($IPC_KEY, 0, 0);
  881.            die if !defined($key);
  882.  
  883.            $semnum = 0;
  884.            $semflag = 0;
  885.  
  886.            # Decrement the semaphore count
  887.            $semop = -1;
  888.            $opstring = pack("sss", $semnum, $semop, $semflag);
  889.  
  890.            semop($key,$opstring) || die "$!";
  891.  
  892. WARNING
  893.        The SysV IPC code above was written long ago, and it's
  894.        definitely clunky looking.  It should at the very least be
  895.        made to use strict and require "sys/ipc.ph".  Better yet,
  896.        perhaps someone should create an IPC::SysV module the way
  897.        we have the Socket module for normal client-server
  898.        communications.
  899.  
  900.        (... time passes)
  901.  
  902.        Voila!  Check out the IPC::SysV modules written by Jack
  903.        Shirazi.  You can find them at a CPAN store near you.
  904.  
  905. NOTES
  906.        If you are running under version 5.000 (dubious) or 5.001,
  907.        you can still use most of the examples in this document.
  908.        You may have to remove the use strict and some of the my()
  909.        statements for 5.000, and for both you'll have to load in
  910.        version 1.2 of the Socket.pm module, which was/is/shall-be
  911.        included in perl5.001o.
  912.  
  913.        Most of these routines quietly but politely return undef
  914.        when they fail instead of causing your program to die
  915.        right then and there due to an uncaught exception.
  916.        (Actually, some of the new Socket conversion functions
  917.        croak() on bad arguments.)  It is therefore essential that
  918.        you should check the return values fo these functions.
  919.        Always begin your socket programs this way for optimal
  920.        success, and don't forget to add -T taint checking flag to
  921.        the pound-bang line for servers:
  922.  
  923.            #!/usr/bin/perl -w
  924.            require 5.002;
  925.            use strict;
  926.            use sigtrap;
  927.            use Socket;
  928.  
  929. BUGS
  930.        All these routines create system-specific portability
  931.        problems.  As noted elsewhere, Perl is at the mercy of
  932.        your C libraries for much of its system behaviour.  It's
  933.        probably safest to assume broken SysV semantics for
  934.        signals and to stick with simple TCP and UDP socket
  935.        operations; e.g. don't try to pass open filedescriptors
  936.        over a local UDP datagram socket if you want your code to
  937.        stand a chance of being portable.
  938.  
  939.        Because few vendors provide C libraries that are safely
  940.        re-entrant, the prudent programmer will do little else
  941.        within a handler beyond die() to raise an exception and
  942.        longjmp(3) out.
  943.  
  944. AUTHOR
  945.        Tom Christiansen, with occasional vestiges of Larry Wall's
  946.        original version.
  947.  
  948. SEE ALSO
  949.        Besides the obvious functions in the perlfunc manpage, you
  950.        should also check out the modules file at your nearest
  951.        CPAN site.  (See the perlmod manpage or best yet, the Perl
  952.        FAQ for a description of what CPAN is and where to get
  953.        it.)  Section 5 of the modules file is devoted to
  954.        "Networking, Device Control (modems) and Interprocess
  955.        Communication", and contains numerous unbundled modules
  956.        numerous networking modules, Chat and Expect operations,
  957.        CGI programming, DCE, FTP, IPC, NNTP, Proxy, Ptty, RPC,
  958.        SNMP, SMTP, Telnet, Threads, and ToolTalk--just to name a
  959.        few.
  960.